﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Services;
using WorkFlowCore.Conditions;
using WorkFlowCore.Plugins;
using WorkFlowCore.Common.Tracers;
using WorkFlowCore.WorkTasks;

namespace WorkFlowCore.UserSelectors
{
    public class UserSelectorManager:IDomainService
    {
        private readonly PluginManager pluginManager;

        public UserSelectorManager(PluginManager pluginManager)
        {
            this.pluginManager = pluginManager;
        }


        /// <summary>
        /// 所有用户选择器
        /// </summary>
        public IReadOnlyList<UserSelector> UserSelectors {

            get
            {
                var result = new List<UserSelector>();
                var configs = pluginManager.GetPluginApplyConfigs(typeof(IUserSelector).FullName).Result;

                foreach (var config in configs.applyConfigs.OrderBy(c => c.Order))
                {
                    var manifest = configs.manifests.Where(m => m.ClassName == config.EntryFullName).FirstOrDefault();
                    if(manifest==null) continue;
                    result.Add(new UserSelector(config.PluginId,string.IsNullOrWhiteSpace(config.Name)? manifest?.Name:config.Name, string.IsNullOrWhiteSpace(config.Description) ? manifest.Description : config.Description, config?.Enabled??true));
                }
                return result;
            }
        }
        /// <summary>
        /// 从 程序集注册
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies"></param>
        public static void RegisterSelector(IServiceCollection services, params Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes().Where(t =>typeof(IUserSelector).IsAssignableFrom(t));

                foreach (var type in types)
                {
                    var attr = type.GetCustomAttribute<UserSelectorAttribute>();
                    var selectorId = type.FullName;
                    var selectorName = attr?.Name ?? type.FullName;
                    services.AddScoped(type);
                    PluginManager.Register(new ManifestWithConfig(selectorId, selectorName, attr?.Description, "", "1.0", assembly));
                }
            }
        }



        /// <summary>
        /// 获取选择器
        /// </summary>
        /// <param name="selectorId"></param>
        /// <returns></returns>
        public virtual IUserSelector GetUserSelector(string selectorId)
        {
            using (var activity = WorkflowActivitySource.Source?.StartActivity("GetUserSelector"))
            {
                return pluginManager.Resolve<IUserSelector>(selectorId);
            }
            
        }

        /// <summary>
        /// 获取默认选择器
        /// </summary>
        /// <returns></returns>
        public virtual IDefaultUserSelector[] GetDefaultUserSelectors()
        {
            var services = pluginManager.ResolveAll<IUserSelector>();
            return services.Where(s=>s is IDefaultUserSelector ).Select(s=>(IDefaultUserSelector)s).ToArray();
        }

        public async Task<List<Selection>> GetUsersOfUserSelecton(string userSelectorId, string[] selectionIds)
        {
            var selector = GetUserSelector(userSelectorId);
            if (selector != null)
            {
                var selections = new List<Selection>();
                foreach (var selectionId in selectionIds)
                {
                    selections.AddRange(selector.GetUsers(new SelectorInput { SelectionId = selectionId }).Select(u => new Selection { Id = u.Id, Name = u.Name }).ToList());
                }
                return selections.Distinct().ToList();
            }
            else
            {
                return new List<Selection> { };
            }
        }
    }
}
